<?php
/**
 *
 * @category   babel 
 * @package    BABEL
 * @author     Hannes Magnusson <hannes.magnusson@gmail.com>
 * @copyright  2008 Team babel
 * @license    LGPL
 */

class PDODB extends PDO {
	private static $instance;

	public static function connect() {
		if (!isset(self::$instance)) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	public function __construct() {
		$config = parse_url(_ICE_DSN);
		if (!strcasecmp($config["scheme"], "mysqli")) {
			$config["scheme"] = substr($config["scheme"], 0, -1);
		}
		$config["path"] = substr($config["path"], 1);
		$dsn = $config["scheme"] . ":host=" . $config["host"] . ";dbname=" . $config["path"];
		if (!isset($config["pass"])) {
			$config["pass"] = null;
		}

		parent::__construct($dsn, $config["user"], $config["pass"], array(
			PDO::ERRMODE_EXCEPTION     => true,
			PDO::ATTR_PERSISTENT       => true,
			PDO::ATTR_EMULATE_PREPARES => true,
		));
	}
	public static function runQuery($query, array $params = null, &$stmt = null) {
		$pdo = self::connect();
		$stmt = $pdo->prepare($query);
		$retval = $stmt->execute($params);
		if (!$retval) {
			Babel_Error_Logger::push($stmt->errorInfo());
			Babel_Error_Logger::push(self::$instance->errorInfo());
		}
		return $retval;
	}
	public static function execQuery($query, array $params = null, &$id = null) {
		if ($params) {
			$retval = self::runQuery($query, $params, $stmt);
		} else {
			$pdo = self::connect();
			$retval = $pdo->query($query);
		}
		if ($retval) {
			$id = self::$instance->lastInsertId();
		} else {
			Babel_Error_Logger::push($stmt->errorInfo());
			Babel_Error_Logger::push(self::$instance->errorInfo());
		}
		return $retval;
	}
	public static function execQueryFetch($query, $mode, $params = null, &$stmt = null) {
		if (self::runQuery($query, $params, $stmt)) {
			return $stmt->fetchAll($mode);
		}
		Babel_Error_Logger::push($stmt->errorInfo());
		throw new Exception("Query failed");
	}

}
